package com.ruoyi.framework.config;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.ijpay.core.kit.PayKit;
import com.ruoyi.framework.config.properties.WxpayPropertis;
import com.ruoyi.framework.interceptor.WxPayInterceptor;
import lombok.AllArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.security.cert.X509Certificate;

/**
 * @author dyun
 */
@Configuration
@AllArgsConstructor
@EnableConfigurationProperties({WxpayPropertis.class})
public class PayConfig implements WebMvcConfigurer {

    public static String serialNo;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new WxPayInterceptor()).addPathPatterns("/wxPay/**");
    }

    /**
     * 解析证书序列号
     */
    public static String getSerialNumber(WxpayPropertis wxpayPropertis) {
        if (StrUtil.isEmpty(serialNo)) {
            // 获取证书序列号
            X509Certificate certificate = PayKit.getCertificate(FileUtil.getInputStream(wxpayPropertis.getPemCertPath()));
            serialNo = certificate.getSerialNumber().toString(16).toUpperCase();
        }
        return serialNo;
    }
}
